package com.itheima.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.utils.CollUtils;
import com.itheima.gateway.config.AuthProperties;
import com.itheima.gateway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;

import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.List;

@Component
@EnableConfigurationProperties(AuthProperties.class)
public class LoginGlobalFliter implements GlobalFilter, Ordered {
    @Autowired
    private JwtTool jwtTool;

    @Autowired
    private AuthProperties authProperties;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //路径拦截
        System.err.println("gateway 网关 LoginGlobalFliter 执行 拦截请求路径 --- time: "+ LocalDateTime.now());

        //1、判断路径
        //获取路径
        ServerHttpRequest request = exchange.getRequest();
        //判断路径是否需要拦截
        Boolean flag = isMatch(request);
        if (flag) {
            //无需拦截，直接放行
            return chain.filter(exchange);
        }

        //2、获取token
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        if (!CollUtils.isEmpty(headers)) {
            token = headers.get(0);
        }

        //校验+解析token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            //无效 拦截并提示前端
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        //TODO token有效，传递信息 将userId传入exchang中
        System.err.println("gateway 网关 LoginGlobalFliter 过滤器中 userInfo= "+userId +" --- time: "+ LocalDateTime.now());
        String uid = userId.toString();
        ServerWebExchange ex = exchange.mutate().request(builder ->
                builder.header("user-info",uid)).build();


        //放行
        return chain.filter(ex);
    }

    private Boolean isMatch(ServerHttpRequest request) {
        String path = request.getPath().toString();
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path))//注意match中的顺序别写错 ,前面的是目标路径,符合目标路径的放行
            {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
